<template>
  <el-dialog v-model="dialogFormVisible" title="修改信息" width="650px" @close="handleClose">
    <el-form ref="adminInfoForm" :model="upAdminInfoV" :rules="upAdminInfoRules" label-width="80px" class="demo-ruleForm"
      size="default" status-icon>
      <div class="card_avatar">
        <img :src="avatar" class="avatar" title="IWu" />
        <el-upload class="upload-demo" ref="uploadRef" 
        v-model:file-list="fileList" 
        action="http://localhost:8080/api/admin/upAdminAvatar" 
        :data="data()" :headers="headers"
         :on-success="handSuccess" :on-exceed="handExceed" :before-upload="beforeAvatarUpload"
         list-type="picture" :auto-upload="false" :limit="1">
        <template #trigger>
          <el-button type="primary" class="upstateAvatar">修改头像</el-button>
        </template>
      </el-upload>
      </div>
      <el-form-item label="姓名" prop="adminName">
        <el-input v-model="upAdminInfoV.adminName" style="width: 240px;" />
      </el-form-item>
      <el-form-item label="电话" prop="adminPhone">
        <el-input v-model="upAdminInfoV.adminPhone" style="width: 240px;" />
      </el-form-item>
      <el-form-item label="邮箱" prop="adminEmail">
        <el-input v-model="upAdminInfoV.adminEmail" style="width: 240px;" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelEdit(adminInfoForm)">取消</el-button>
        <el-button type="primary" @click="saveInfo(adminInfoForm)">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import { elmessage, data } from "@/hook/hook"
import { reactive, ref, computed, onBeforeMount } from 'vue'
import  {upAdminInfo} from "@/api/adminApi"
import {upAdminInfoRules,upAdminInfoV} from "@/utills/adminValidators"
import type { FormInstance, FormRules } from 'element-plus'
import { UploadProps, UploadUserFile, UploadInstance, genFileId, UploadRawFile, ElMessage } from 'element-plus'
import { useStore } from "vuex"
import { useRouter } from "vue-router"
import { loginOu } from "@/api/authApi"
const props = defineProps(["dialogFormVisible", "handleCloseDialog"])

const fileList = ref<UploadUserFile[]>([])
const store = useStore()
const router = useRouter()
const adminInfoForm = ref<FormInstance>()

const admin =store.state.adminState.admin
const avatar = ref()
// 用户头像上传
const uploadRef = ref<UploadInstance>()
// 设置上传头像所需的头部内容
const headers = reactive({
  Authorization: localStorage.getItem("loginData") ? JSON.parse(localStorage.getItem("loginData") || "").token : null,
})

const handExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}
const handSuccess: UploadProps['onSuccess'] = (response: any, UploadFile: any, UploadFiles: any) => {
  // 上传成功后将头像更换
  // console.log(UploadFile.raw);
  admin.adminAvatar = window.URL.createObjectURL(UploadFile.raw)
  fileList.value = []
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
 
  
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }

  
  return true
}
const handleClose = () => {
  props.handleCloseDialog()
}
// 提交按钮
const saveInfo = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 将图片上传到数据库
      if (uploadRef.value != null) {
        uploadRef.value!.submit()
      }
      
      store.commit("upAdminInfo", upAdminInfoV)
      const newData = {
        ...data(),
        adminName:upAdminInfoV.adminName,
        adminEmail:upAdminInfoV.adminEmail,
        adminPhone:upAdminInfoV.adminPhone,
      }
      await upAdminInfo(newData).then((res: any) => {
        if (res.data["code"] == "200") {
          elmessage(res.data["message"], res.data["type"])
        }
        else if (res.data["code"] == "201") {
          elmessage(res.data["message"], res.data["type"])
          setTimeout(() => {
            router.replace("/admin")
          }, 500);
          loginOu(data())
          localStorage.clear()
        }
        else if (res.data["code"] == "300") {
          elmessage(res.data["message"], res.data["type"])
          setTimeout(() => {
            router.replace("/admin")
          }, 500);
          localStorage.clear()
        }
        else {
          console.log(res.data["message"]);

        }
      })


    } else {
      console.log('error submit!', fields)
    }
  })
  props.handleCloseDialog()
}
// 取消按钮
const cancelEdit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  props.handleCloseDialog()

}
const initData = () => {
  upAdminInfoV.adminId = admin.adminId
  upAdminInfoV.adminName = admin.adminName
  upAdminInfoV.adminEmail = admin.adminEmail
  upAdminInfoV.adminPhone = admin.adminPhone

}

onBeforeMount(() => {
  initData()
  avatar.value = admin.adminAvatar
})

</script>
<style scoped>
.upload-demo {

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

.card_avatar {
  z-index: 99;
  position: absolute;
  margin-left: 390px;
  /* margin-top: 20px; */
  width: 150px;

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

.avatar {
  margin-bottom: 10px;
  height: 90px;
  width: 90px;
  border-radius: 100%;

}

.demo-ruleForm {
  position: relative;
  height: 250px;
}
</style>